import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
import Index from '@/pages/Index/Index'
import Login from '@/pages/Login/Login'
import List from '@/pages/List/List'
import Post from '@/pages/Post/Post'
import Detail from '@/pages/Detail/Detail'
import About from '@/pages/About/About'
import Search from '@/pages/Search/Search'
import Error from '@/pages/Error/Error'
import Home from '@/pages/Home/Home'

import { Notification } from 'element-ui';
Vue.prototype.$notification = Notification;

Vue.use(Router)

const routes = [
  {
    path: '/',
    name: 'Index',
    component: Index
  },
  {
    path:'/index',
    redirect:'/'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/list',
    name: 'List',
    component: List
  },
  {
    path:'/post',
    name:'Post',
    component:Post
  },
  {
    path:'/detail',
    name:'Detail',
    component:Detail
  },
  {
    path:'/about',
    name:'About',
    component:About
  },
  {
    path:'/search',
    name:'Search',
    component:Search
  },
  {
    path:'/home',
    name:'Home',
    component:Home
  },
  {
    path: '*',
    name: 'error',
    component: Error
  }
]

const router = new Router({
  routes
})

// 挂载全局路由导航守卫
router.beforeEach((to,from,next) => {
  // to：将要访问的路径
  // from：从哪个路径跳转而来
  // next：是一个函数，表示放行

  if(to.path !== '/post' && to.path !== '/home') return next();
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token');
  if(!tokenStr){
    Notification({
        title: '您还未登录',
        message: '您暂时无法发帖、回帖及查看个人主页，请登录！',
        type: 'warning'
    });
    return next('/login');
  }
  next();
})

//获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}

export default router
